﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Shop.Managers;
using Shop.Mappers;
using Entity.Baskets;

namespace Shop.Controllers
{
    public class OrdersController : Controller
    {
        private IManagerProduct managerProduct;
        private IManagerBasket managerBasket;

        public OrdersController(IManagerBasket managerBasket, IManagerProduct managerProduct)
        {
            this.managerBasket = managerBasket;
            this.managerProduct = managerProduct;
        }

        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetBasketJson()
        {
            List<Models.Basket> listBasketNotOrdered = new List<Models.Basket>();

            List<Entity.Baskets.Basket> basketList = managerBasket.
                GetAllOrdersForUser(ShopMembership.WebSecurity.User.Identity.Name, State.NotOrdered).ToList();

            foreach (Entity.Baskets.Basket basket in basketList)
                if (basket.StateValue == (int)Entity.Baskets.State.NotOrdered)
                {
                    List<Shop.Models.OrderPosition> orderPos = new List<Shop.Models.OrderPosition>();
                    foreach (var v in basket.OrderPosition)
                        orderPos.Add(new Models.OrderPosition() { Product = v.Product.Name, Count = v.Count });

                    listBasketNotOrdered.Add(new Models.Basket() { Id = basket.Id, OrderPosition = orderPos, User = basket.User.Username });
                }

            return Json(listBasketNotOrdered, JsonRequestBehavior.AllowGet);
        }

        
        public ActionResult AddNewProduct(string IdProduct)
        {
            managerBasket.AddNewProduct(managerProduct.Find(Int32.Parse(IdProduct)), ShopMembership.WebSecurity.User.Identity.Name);
            return RedirectToAction("Index");
        }

        
        public ActionResult Delete(string IdOrderProsition)
        {
            managerBasket.DeleteOrderPosition(Int32.Parse(IdOrderProsition));
            return RedirectToAction("Index");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SubmitOrder()
        {
            managerBasket.SubmitOrder(ShopMembership.WebSecurity.User.Identity.Name);
            return RedirectToAction("Index");
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteBasket(string Id)
        {
            managerBasket.DeleteBasket(Int32.Parse(Id));
            return RedirectToAction("Index");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetPrice()
        {
            var price = new { Price = managerBasket.GetPrice(ShopMembership.WebSecurity.User.Identity.Name) };
            return Json(price, JsonRequestBehavior.AllowGet);
        }
    }
}
